<template>
  <div>
    <HeaderNav :title="$t('m.headernav.ADDPHOTO')" :showBack="true" />
    <div class="img_container">
      <img v-if="filePath" :src='filePath' class="img"/>
      <div v-else class="img" ></div>
    </div>
    
    
    <van-uploader :before-read="beforeRead">
      <div class="addphoto_btn">{{$t('m.msg.SELECTPHOTO')}}</div>
    </van-uploader>
   <div class="addphoto_btn" @click="uploadImg()" >{{$t('m.msg.UPLOADPOTO')}}</div>
  </div>
</template>

<script>
import {
    Uploader  
} from 'vant';
import HeaderNav from '@/components/HeaderNav.vue'
import Footer from '@/components/Footer.vue'
import {postQuery, getQuery} from '@/api/query';
import {setUser, getUser} from '@/api/session';
export default {
  name: 'addPhoto',
  components: {
      [Uploader.name]: Uploader,
      HeaderNav
     
  },
  data(){
    return {
      file: {},
      filePath: ''
      
    }
  },
  methods: {
    // 返回布尔值
    beforeRead(file) {
      let that = this;
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        that.$toast.fail(that.$i18n.t('m.msg.MSG1'));
        return false;
      }
      if(file.size >= 3145728){
        that.$toast.fail(that.$i18n.t('m.msg.MSG2'));
        return false;
      }
      var reader = new FileReader();　　　　//实例化
      reader.readAsDataURL(file);　　　　　　//加载
      reader.onload = function () {
        that.filePath = this.result;       
      }
      that.file = file;
      return true;
    },
    uploadImg(){
      var that = this;
      if(!that.file && !that.filePath){
        that.$toast.fail(that.$i18n.t('m.msg.MSG3'));
        return
      }
      var fd = new FormData()
      fd.append('file', that.file)
      postQuery('/member/update/avatar', fd)
        .then (res => {
          console.log(res)
          if(res.code == 200){
            that.$toast.success(that.$i18n.t('m.msg.MSG4'));
            setUser(null, 2); //修改完成更新缓存数据
          }else{
            that.$toast.fail(res.msg);
          }
      })
    }
  },
  created: function() {
    this.filePath = getUser().httpAvatar;
  }
}
</script>
<style scoped>
  .img_container{
    height: 46vh;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #a1a1a1;
    margin-top: 30px;
  }
  .img{
    height: 43vh;
    width: 74vw;
    background-color: white;
    border: 1px #a1a1a1 dashed; 
  }
  .addphoto_btn{
    height: 90px;
    width: 90vw;
    margin: 5vh 0 0 5vw;
    background-color: #01D2FF;
    color: white;
    font-size: 36px;
    border-radius: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
